package com.fy.utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DocumentConverter {

  /**
   * Word转HTML的具体实现
   */
  public static String convertWordToHtml(XWPFDocument document) {
    try {
      StringBuilder html = new StringBuilder();
      html.append("<html><body>");

      // 遍历段落
      for (XWPFParagraph paragraph : document.getParagraphs()) {
        String text = paragraph.getText();
        log.debug("Converting paragraph: {}", text);
        html.append("<p>").append(text).append("</p>");
      }

      // 遍历表格
      for (XWPFTable table : document.getTables()) {
        html.append("<table border='1'>");
        for (XWPFTableRow row : table.getRows()) {
          html.append("<tr>");
          for (XWPFTableCell cell : row.getTableCells()) {
            html.append("<td>").append(cell.getText()).append("</td>");
          }
          html.append("</tr>");
        }
        html.append("</table>");
      }

      html.append("</body></html>");
      String result = html.toString();
      log.debug("Converted HTML: {}", result);
      return result;
    } catch (Exception e) {
      log.error("Word转HTML失败", e);
      throw new RuntimeException("文档转换失败", e);
    }
  }

  /**
   * Excel转HTML的具体实现
   */
  public static String convertExcelToHtml(XSSFWorkbook workbook) {
    StringBuilder html = new StringBuilder();
    html.append("<html><body>");

    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
      XSSFSheet sheet = workbook.getSheetAt(i);
      html.append("<h2>").append(sheet.getSheetName()).append("</h2>");
      html.append("<table border='1'>");

      for (Row row : sheet) {
        html.append("<tr>");
        for (Cell cell : row) {
          html.append("<td>");
          switch (cell.getCellType()) {
            case STRING:
              html.append(cell.getStringCellValue());
              break;
            case NUMERIC:
              html.append(cell.getNumericCellValue());
              break;
            // 处理其他类型...
          }
          html.append("</td>");
        }
        html.append("</tr>");
      }

      html.append("</table>");
    }

    html.append("</body></html>");
    return html.toString();
  }
}